//
//  KyNetworkManager.swift
//  KySwiftPro
//
//  Created by fangyukui on 2017/10/23.
//  Copyright © 2017年 fangyukui. All rights reserved.
//

import UIKit
import AFNetworking

enum HttpMethod {
    case GET
    case POST
}

class KyNetworkManager: AFHTTPSessionManager {
    
    static let shared : KyNetworkManager = {
        let instance = KyNetworkManager()
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return instance
    }()
    
    var access_token:String?  //= "2.00Vk6U5DEUrD8E9a4553fe0c6bedQB"
    
    
    
    var isUserLogin : Bool{
        return access_token == nil ? false : true
    }
    
    
    open func tokenRequest(method:HttpMethod = .GET,URLString:String,params:[String:Any]?,complete:@escaping (_ json:Any?,_ isSucess:Bool)->()) -> Void {
        
        guard let tocken = access_token  else {
            print("没有access_token")
            //FIXME:access_token过期！ 通知用户登录
            complete(nil,false)
            return;
        }
        var inner_params = params
        if inner_params == nil {
           inner_params = [String:Any]()
            
        }
        inner_params!["access_token"] = tocken
        
      
        
        request(method: method, URLString: URLString, params: inner_params) { (json, isSucess) in
            complete(json, isSucess)
            
        }
        
        
    }
    
    
    open func request(method:HttpMethod = .GET,URLString:String,params:[String:Any]?,complete:@escaping (_ json:Any?,_ isSucess:Bool)->()) -> Void {
        
        let sucessBlock = {(dataTask:URLSessionDataTask,json:Any)-> Void in
            complete(json, true)
            KyLog(message: json)
            
        }
        let failureBlock = {(dataTask:URLSessionDataTask?,error:Error)-> Void in
            KyLog(message: "错误信息：\(error)")
            if (dataTask?.response as? HTTPURLResponse)?.statusCode == 403 {
                //FIXME:access_token过期！ 通知用户登录
                print("服务器访问错误")
            }
        
            complete(nil, false)
        }
       
        
        if method == .GET {
            get(URLString, parameters: params, progress: nil, success: sucessBlock, failure: failureBlock)
        }else{
            post(URLString, parameters: params, progress: nil, success: sucessBlock, failure: failureBlock)
        }
    }
    

}
